package com.huasan.www.demon.rest.resource;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.glassfish.jersey.server.mvc.Viewable;
import org.springframework.beans.factory.annotation.Autowired;

import com.huasan.www.demon.data.service.UserdetailService;
import com.huasan.www.demon.data.service.UserinfoService;
import com.huasan.www.demon.pojo.Userdetail;
import com.huasan.www.demon.pojo.UserdetailExample;
import com.huasan.www.demon.pojo.Userinfo;
import com.huasan.www.demon.util.DataTableUtil;
import com.huasan.www.demon.util.ExcelUtil;
import com.huasan.www.demon.util.OnePage;

@Path("/userdetail")
public class UserdetailResource extends Resource{

	@Autowired
	private UserdetailService userdetailService;
	
	@Autowired
	private UserinfoService userinfoService;
	
	private Userdetail userdetail;
	
	private static final Map<String,String> optMap = new HashMap<String,String>(){
		private static final long serialVersionUID = 1L;

	{
		put("10086","中国移动");
		put("189","中国电信");
		put("10010","中国联通");
	}};
	
	@GET
	@Path("/user/{id}")
	@Produces("text/html")
	public Viewable getDetailByUid(@PathParam("id") Integer userid){
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("userid", userid);
		return getView("userdetail", map);
	}
	
	@GET
	@Path("/account/{id}")
	@Produces("text/html")
	public Viewable getDetailByAccountId(@PathParam("id") Integer accountid){
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("accountid", accountid);
		return getView("accountdetail", map);
	}
	
	@POST
	@Path("/download")
	@Produces({ "application/vnd.ms-excel" })
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public void downloadUserDetail(@FormParam("userid") Integer userid){
		try {
			Userinfo user = userinfoService.selectByPrimaryKey(userid.longValue());
			UserdetailExample example = new UserdetailExample();
			UserdetailExample.Criteria criteria =  example.createCriteria();
			example.setOrderByClause(" logintime desc ");
			criteria.andUseridEqualTo(userid.longValue());
			List <Userdetail> list = userdetailService.selectByExample(example);
			String[] heads = {"登录时间","上网开始时间", "上网结束时间", "运营商"};
			String[][] data = new String[list.size()][4];
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for ( int i=0; i<list.size(); i++ ){
				Userdetail detail = list.get(i);
				data[i][0] = detail.getLogintime()==null?"":sdf.format(detail.getLogintime());
				data[i][1] = detail.getChargetime()==null?"":sdf.format(detail.getChargetime());
				data[i][2] = detail.getEndtime()==null?"":sdf.format(detail.getEndtime());
				data[i][3] = optMap.get(detail.getOptcode());
			}
			
			httpServletResponse.setHeader("Content-Disposition", "attachment;filename=\""
					+ new String("用户上网数据.xls".getBytes("gbk"), "iso-8859-1") + "\"");
			ExcelUtil xls = new ExcelUtil();
			OutputStream out =httpServletResponse.getOutputStream();
			xls.writeXls("用户("+(user==null?"":user.getLoginname())+")使用明细", heads, data, out);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
//		return null;
	}
	
	@POST
	@Path("/userdetail")
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getUserDetail(@FormParam("userid") Integer userid,
			@FormParam("sEcho") String sEcho,
			@FormParam("iDisplayStart") Integer iDisplayStart,
			@FormParam("iDisplayLength") Integer iDisplayLength,
			@FormParam("sSearch") String sSearch
				) throws JsonGenerationException, JsonMappingException, IOException{
		UserdetailExample example = new UserdetailExample();
		UserdetailExample.Criteria criteria = example.createCriteria();
		criteria.andUseridEqualTo(userid.longValue());
		example.setOrderByClause("logintime desc, chargetime desc, alivetime desc, endtime desc");
		Integer total = userdetailService.countByExample(example);
		example.setLimitStart(iDisplayStart);
		example.setLimitEnd(iDisplayLength);
		OnePage<Userdetail> page = userdetailService.selectOnePageByExample(example);
		return DataTableUtil.getDataTable(sEcho, total, total
				, objectmapper.writeValueAsString(page.getDataList()));
	}
	
	@POST
	@Path("/accountdetail")
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String getAccountDetail(@FormParam("accountid") Integer accountid,
			@FormParam("sEcho") String sEcho,
			@FormParam("iDisplayStart") Integer iDisplayStart,
			@FormParam("iDisplayLength") Integer iDisplayLength,
			@FormParam("sSearch") String sSearch
				) throws JsonGenerationException, JsonMappingException, IOException{
		UserdetailExample example = new UserdetailExample();
		UserdetailExample.Criteria criteria = example.createCriteria();
		criteria.andAccountidEqualTo(accountid.longValue());
		example.setOrderByClause("logintime desc, chargetime desc, alivetime desc, endtime desc");
		Integer total = userdetailService.countByExample(example);
		example.setLimitStart(iDisplayStart);
		example.setLimitEnd(iDisplayLength);
		OnePage<Userdetail> page = userdetailService.selectOnePageByExample(example);
		return DataTableUtil.getDataTable(sEcho, total, total
				, objectmapper.writeValueAsString(page.getDataList()));
	}
	
	public Userdetail getUserdetail() {
		return userdetail;
	}

	public void setUserdetail(Userdetail userdetail) {
		this.userdetail = userdetail;
	}
	
}
